package Json

import "encoding/json"

func BuildJson(data interface{}) string {
	code, err := json.Marshal(data)
	if err != nil {
		return ""
	}
	return string(code)
}

func BuildMapByJson(jsn string) map[string]interface{} {
	var data map[string]interface{}
	err := json.Unmarshal([]byte(jsn), &data)
	if err != nil {
		return nil
	}

	return data
}

func BuildMapListByJson(jsn string) []map[string]interface{} {
	data := make([]map[string]interface{}, 0)
	err := json.Unmarshal([]byte(jsn), &data)
	if err != nil {
		return nil
	}

	return data
}

func BuildMap(data interface{}) map[string]interface{} {
	jsn := BuildJson(data)
	if len(jsn) == 0 {
		return nil
	}

	return BuildMapByJson(jsn)
}

func BuildObjectByMap(mapData interface{}, objData interface{}) error {
	jsn := BuildJson(mapData)
	if len(jsn) == 0 {
		return nil
	}

	err := json.Unmarshal([]byte(jsn), &objData)
	if err != nil {
		return err
	}

	return nil
}

func Clone(data any, clone any) error {
	jsn, err := json.Marshal(data)
	if err != nil {
		return err
	}

	err = json.Unmarshal([]byte(jsn), &clone)
	if err != nil {
		return err
	}

	return nil
}
